from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.views import generic
import redis

from . import models
from cart.forms import AddProductForm
from shop.services.redis_client import RedisClient


r = redis.StrictRedis(host='localhost', port=6379, db=0)


class DisplayingListProducts(generic.View):

    def get(self, request, slug=None):

        category = None
        categories = models.Category.objects.all() 
        products = models.Product.objects.filter(available=True)

        if slug:
            category = get_object_or_404(models.Category, slug=slug)
            products = products.filter(category=category)

        context = {'category': category,
                   'categories': categories,
                   'products': products}
        
        return render(request, 'shop/product/list.html', context)


class DisplayingProduct(generic.View):

    def get(self, request, id, slug):

        product = get_object_or_404(models.Product, id=id, slug=slug)
        add_product_form = AddProductForm()

        redis_client = RedisClient()
        number_views = redis_client.increase_number_views(request, product)

        context = {'product': product,
                   'add_product_form': add_product_form,
                   'number_views': number_views}

        return render(request, 'shop/product/detail.html', context)
